/*
 * @Description: 数据库模块（数据库加载基于 nodejs-orm2 库加载）
 * @Author: pinus
 * @Email: pinus0716@163.com
 * @Git: https://gitee.com/xyf97
 * @Date: 2021-10-06 18:15:30
 * @LastEditTime: 2021-10-09 18:49:13
 */

const path = require('path')
const { Sequelize, DataTypes } = require('sequelize')
const initModels = require(path.join(process.cwd(), '/models/init-models.js'))

/**
 * @description: 初始化连接数据库
 * @param {*} app - express的服务
 * @param {Function} callback
 * @return {*}
 */
async function initialize(app, callback) {
  // 加载配置文件
  const config = require('config').get('db_config')
  const opts = {
    database: config.get('database'),
    username: config.get('username'),
    password: config.get('password'),
    protocol: config.get('protocol'),
    host: config.get('host'),
    port: config.get('port')
  }

  // 连接到数据库
  const db = new Sequelize(opts.database, opts.username, opts.password, {
    host: opts.host,
    port: opts.port,
    dialect: opts.protocol,
    define: {
      timestamps: false // 禁用时间戳
    }
  })
  // 测试连接
  db.authenticate()
    .then(() => {
      console.log('>> 连接成功 Connection has been established successfully.')

      // 加载模型
      const models = initModels(db)
      // console.log(db.models)
      // console.log(models)
      db.models = models
      console.log('>> 已加载模型:')
      console.log(db.models)
      app.db = db
      global.database = db

      // const { list } = require(path.join(process.cwd(), '/dao/DAO.js'))
      // list('ManagerModel', { offset: 1, limit: 2 }, (err, result) => {
      //   console.log(result.length)
      // })
    })
    .catch(err => callback(err))
}

module.exports.initialize = initialize
module.exports.getDataBase = function () {
  return global.database
}
